﻿var mapdatajson = [{
	"name": "北京",
	"log": "116.405285",
	"lat": "39.904989"
},
{
	"name": "上海",
	"log": "121.48",
	"lat": "31.22"
},
{
	"name": "天津",
	"log": "117.2",
	"lat": "39.13"
},
{
	"name": "重庆",
	"log": "106.54",
	"lat": "29.59"
},
{
	"name": "河北",
	"log": "114.48",
	"lat": "38.03"
},
{
	"name": "山西",
	"log": "112.53",
	"lat": "37.87"
},
{
	"name": "辽宁",
	"log": "123.38",
	"lat": "41.8"
},
{
	"name": "吉林",
	"log": "125.35",
	"lat": "43.88"
},
{
	"name": "黑龙江",
	"log": "126.63",
	"lat": "45.75"
},
{
	"name": "浙江",
	"log": "120.19",
	"lat": "30.26"
},
{
	"name": "福建",
	"log": "119.3",
	"lat": "26.08"
},
{
	"name": "山东",
	"log": "106.54",
	"lat": "29.59"
},
{
	"name": "河南",
	"log": "113.65",
	"lat": "34.76"
},
{
	"name": "湖北",
	"log": "114.31",
	"lat": "30.52"
},
{
	"name": "湖南",
	"log": "113",
	"lat": "28.21"
},
{
	"name": "广东",
	"log": "113.23",
	"lat": "23.16"
},
{
	"name": "海南",
	"log": "110.35",
	"lat": "20.02"
},
{
	"name": "四川",
	"log": "104.06",
	"lat": "30.67"
},
{
	"name": "贵州",
	"log": "106.71",
	"lat": "26.57"
},
{
	"name": "云南",
	"log": "102.73",
	"lat": "25.04"
},
{
	"name": "江西",
	"log": "115.89",
	"lat": "28.68"
},
{
	"name": "陕西",
	"log": "108.95",
	"lat": "34.27"
},
{
	"name": "青海",
	"log": "101.74",
	"lat": "36.56"
},
{
	"name": "甘肃",
	"log": "103.73",
	"lat": "36.03"
},
{
	"name": "广西",
	"log": "106.54",
	"lat": "29.59"
},
{
	"name": "新疆",
	"log": "87.68",
	"lat": "43.77"
},
{
	"name": "内蒙古",
	"log": "111.65",
	"lat": "40.82"
},
{
	"name": "西藏",
	"log": "91.11",
	"lat": "29.97"
},
{
	"name": "宁夏",
	"log": "106.27",
	"lat": "38.47"
},
{
	"name": "台湾",
	"log": "121.5",
	"lat": "25.14"
},
{
	"name": "香港",
	"log": "114.1",
	"lat": "22.2"
},
{
	"name": "澳门",
	"log": "113.33",
	"lat": "22.13"
},
{
	"name": "安徽",
	"log": "117.27",
	"lat": "31.86"
},
{
	"name": "江苏",
	"log": "118.78",
	"lat": "32.04"
}
]

var seriesData = [];

window.reloadGatewayStatisticEvent = null;

function createmap(table) {

	if (location.pathname == "/") {
		$.get("/iToolDashboard/GatewayStatistic").then(res => {
			if (res) {
				for (var i in res.provinceTypes) { //用javascript的for/in循环遍历对象的属性
					var replist = {
						name: i.replace("省", "").replace("市", ""),
						value: res.provinceTypes[i],
					};
					seriesData.push(replist);
				}

				$("#activeUserDay").html(res.dayOnlineCount); //日活用户
				$("#onlineUser").html(res.onlineCount);


				if (window.reloadGatewayStatisticEvent) {
					clearInterval(window.reloadGatewayStatisticEvent);
				}

				QPSEcharts(res.cloudFunction, res.httpRequest); //QPS
				ClientEnvironmentEcharts(res.platformTypes) //客户端环境
				ClienttypeEcharts(res.clientTypes) //客户端类型

				UserCityMap(seriesData);
			}
		});
	}

	if (table) {
		ResponseTimeEcharts(table[0].StateResponseTime); //有状态平均响应时长
		WResponseTimeEcharts(table[0].StateResponseTime); //无状态平均响应时长
		failureRateEcharts(table[2].FailureRate); //故障率
		FunctionGdpEcharts(table[1].StateGDP); //函数占比

		$.each(table[3].FailureRateFun, function (i, n) {
			var name = n.requestFunctionName ? "" : n.requestFunctionName;
			var $tr = $("<tr>" +
				"<td>" + n.requestModuleName + "</td>" +
				"<td>" + name + "</td>" +
				"<td>" + n.runCount + "</td>" +
				"</tr>");
			var $table = $("#fungzl");
			$table.append($tr);
		});
	}

}

function userCount(data) {
	///列表
	$.each(data, function (i, n) {

		var $tr = $("<tr>" +
			"<td>" + "<a href='/servers'>" + n.ip + "</a></td>" +
			"<td>" + n.mem + "</td>" +
			"<td>" + n.cpu + "</td>" +
			"</tr>");
		var $table = $("#datas");
		$table.append($tr);
		$.each(n.serviceInstances, function (i, s) {

			var $trs = $("<tr>" +
				"<td>" + s.title + "</td>" +
				"<td>" + s.cpu + "</td>" +
				"<td>" + s.memory + "</td>" +
				"</tr>");
			var $tables = $("#tableservice");
			$tables.append($trs);
		});
	});
}

function convertDats(data) {
	data = data || [];
	var result = [];
	$.each(data, function (i, val) {
		let target = mapdatajson.find(ee => ee.name == val.name)
		if (target) {
			var replists = {
				name: target.name,
				value: [parseFloat(target.log), parseFloat(target.lat), parseFloat(val.value)],
			};
			result.push(replists);
		}
	})
	return result;


};

function QPSEcharts(inputCloudFunction, inputHttpRequest) {

	inputCloudFunction = inputCloudFunction || [];
	inputHttpRequest = inputHttpRequest || [];
	let xtimes1 = [], xtimes2 = [],
		httpRequestData = [],
		cloudFunctionData = [];

	if (inputHttpRequest) {
		httpRequestData = qpsDataListFormat(inputHttpRequest)
		xtimes1 = qpsXTimeListFormat(inputHttpRequest)
	}

	if (inputCloudFunction) {
		cloudFunctionData = qpsDataListFormat(inputCloudFunction);
		//xtimes2 = qpsXTimeListFormat(inputCloudFunction);
	}


	console.error('xtimes', xtimes1)

	let option = {
		title: {
			text: 'QPS'
		},
		tooltip: {
			trigger: 'axis'
		},
		legend: {},
		xAxis: {
			type: 'category',
			boundaryGap: false,
			data: xtimes1
		},
		yAxis: {
			type: 'value'
		},
		series: [
			{
				name: 'Call Http Request',
				type: 'line',
				data: httpRequestData,
				showSymbol: false,
				markPoint: {
					data: [
						{ type: 'max', name: 'Max' }
					]
				},
				markLine: {
					data: [{ type: 'average', name: 'Avg' }]
				}
			},
			{
				name: 'Call Cloud Function',
				type: 'line',
				data: cloudFunctionData,
				showSymbol: false,
				markPoint: {
					data: [
						{ type: 'max', name: 'max' }
					]
				},
				markLine: {
					data: [
						{ type: 'average', name: 'Avg' }
					]
				}
			}
		]
	};

	window.reloadGatewayStatisticEvent = setInterval(function () {
		if (location.pathname == "/") {
			$.get("/iToolDashboard/GatewayStatistic").then(res => {
				if (res) {
					cloudFunctionData = qpsDataListFormat(res.cloudFunction);
					httpRequestData = qpsDataListFormat(res.httpRequest)
					xtimes1 = qpsXTimeListFormat(res.httpRequest)
					//xtimes2 = qpsXTimeListFormat(res.cloudFunction);

					window.myChartzHEXTU.setOption({
						xAxis: {
							data: xtimes1
						},
						series: [{
							data: httpRequestData
						},
						{
							data: cloudFunctionData
						}]
					});
					//刷新数据
					seriesData = [];
					for (var i in res.provinceTypes) { //用javascript的for/in循环遍历对象的属性
						var replist = {
							name: i.replace("省", "").replace("市", ""),
							value: res.provinceTypes[i],
						};
						seriesData.push(replist);
					}

					$("#activeUserDay").html(res.dayOnlineCount);
					$("#onlineUser").html(res.onlineCount);

					ClientEnvironmentEcharts(res.platformTypes) //客户端环境
					ClienttypeEcharts(res.clientTypes) //客户端类型
					UserCityMap(seriesData); //地图
				}
			});
		}
	}, 3000);

	window.myChartzHEXTU = echarts.init(document.getElementById('zhextu'));
	window.myChartzHEXTU.setOption(option);


}

function qpsXTimeListFormat(inputList) {
	inputList = inputList || [];
	inputList.sort(function (a, b) {
		return a.key - b.key;
	});
	let result = inputList.map(item => {
		let time = new Date(item.key);
		time = new Date(time.setHours(time.getHours() + 8))

		let hours = time.getHours() - 0;
		let minutes = time.getMinutes() - 0;
		let secounds = time.getSeconds() - 0;
		hours = hours > 9 ? hours : '0' + hours;
		minutes = minutes > 9 ? minutes : '0' + minutes;
		secounds = secounds > 9 ? secounds : '0' + secounds;
		return hours + ':' + minutes + ':' + secounds;

		return time;
	});

	return result;
}
	function qpsDataListFormat(inputList) {

	inputList = inputList || [];
	inputList.sort(function (a, b) {
		return a.key - b.key;
	});

	let result = inputList.map(item => {
		return item.value;
	});

	return result;
}

function FunctionGdpEcharts(StateGDP) {
	var wztfun = 0,
		yztfun = 0;

	if (StateGDP.length > 0) {
		var wzt = 0,
			yzt = 0;
		var yztdata = StateGDP.find(a => a.isUseState);
		if (yztdata) {
			yzt = yztdata.runCount ? yztdata.runCount : 0;
		}
		var wztdata = StateGDP.find(a => !a.isUseState);
		if (wztdata) {
			wzt = wztdata.runCount ? wztdata.runCount : 0;
		}
		yztfun = yzt / (wzt + yzt) * 100;
		wztfun = wzt / (wzt + yzt) * 100;
	}
	var pass_rate = yztfun ? yztfun.toFixed(2) : 0,
		average = wztfun ? wztfun.toFixed(2) : 0,
		total = 100;
	var option = {
		title: {
			text: '运行占比'
		},
		tooltip: {
			show: false,
			trigger: 'item',
			formatter: "{a} : {c} ({d}%)"
		},
		//  color: ['#85b6b2', '#6d4f8d'],
		color: ['#c3e58c', '#4b95f1'],
		legend: {
			orient: 'vertical',
			right: '0%',
			bottom: '20%',
			itemHeight: 14, //图例的高度
			itemGap: 8, //图例之间的间距
			data: ['有状态' + pass_rate + '%', '无状态' + average + '%']
			//图例的名字需要和饼图的name一致，才会显示图例
		},
		series: [{
			name: '有状态' + pass_rate + '%',
			type: 'pie',
			radius: ['40%', '45%'],
			emphasis: {
				label: {
					show: true,
					fontSize: '20',
					fontWeight: 'bold'
				}
			},
			data: [{
				value: pass_rate, //需要显示的数据
				name: '有状态' + pass_rate + '%',
				itemStyle: {
					normal: {
						color: '#c3e58c'
					}
				}
			},
			{
				value: total - pass_rate,
				//不需要显示的数据，颜色设置成和背景一样
				itemStyle: {
					normal: {
						color: 'transparent'
					}
				}
			}
			]
		},
		{
			name: '无状态' + average + '%',
			type: 'pie',
			radius: ['30%', '35%'],
			label: {
				show: false,
				position: 'center',
				// normal: {
				//     position: 'inner'
				// }
			},
			labelLine: {
				normal: {
					show: false
				}
			},
			emphasis: {
				label: {
					show: true,
					fontSize: '20',
					fontWeight: 'bold'
				}
			},
			data: [{
				name: '无状态' + average + '%',
				value: average,
				itemStyle: {
					normal: {
						color: '#4b95f1'
					}
				}
			},
			{
				value: total - average,
				itemStyle: {
					normal: {
						color: 'transparent'
					}
				}
			}
			]
		}
		]
	};
	window.myChartSTATEZB = echarts.init(document.getElementById('statezb'));
	window.myChartSTATEZB.setOption(option);
}

///子弹图
function ResponseTimeEcharts(StateResponseTime) {

	var value = 100;
	if (StateResponseTime) {
		var valuedata = StateResponseTime.find(a => a.isUseState);
		if (valuedata) {
			value = valuedata.runTime ? valuedata.runTime : 100;
		}
		count = value ? value + 300 : 60;
	}
	var option = {
		title: {
			text: "有状态",
		},
		yAxis: [{
			type: 'category',
			data: ['AVG'],
			axisLine: {
				show: false
			},
			axisTick: {
				show: false
			}
		}, {
			type: 'category',
			data: [''],
			axisLine: {
				show: false
			},
			axisTick: {
				show: false
			}
		}],
		xAxis: {
			type: 'value',
			axisLabel: {
				formatter: '{value}ms'
			},
			axisLine: {
				show: false
			},
			axisTick: {
				show: false
			}
		},
		tooltip: {
			formatter: '{a}: {c}'
		},
		legend: {
			selectedMode: false,
			right: 0,
			top: 20
		},
		grid: {
			containLabel: true,
			width: "96%",
			height: 60,
			left: 10,
			top: 80
		},
		series: [{
			name: "响应时长 ms",
			data: [value],
			type: 'bar',
			yAxisIndex: 0,
			stack: "range",
			silent: true,
			barWidth: 90,
			color: "#c3e58c"
		}]
	};
	window.myChartYZTZDTU = echarts.init(document.getElementById('yztzdtu'));
	window.myChartYZTZDTU.setOption(option);
}

function WResponseTimeEcharts(StateResponseTime) {

	var value = 100;
	if (StateResponseTime) {
		var valuedata = StateResponseTime.find(a => !a.isUseState);
		if (valuedata) {
			value = valuedata.runTime ? valuedata.runTime : 100;
		}
	}
	var option = {
		title: {
			text: "无状态",
		},
		yAxis: [{
			type: 'category',
			data: ['AVG'],
			axisLine: {
				show: false
			},
			axisTick: {
				show: false
			}
		}, {
			type: 'category',
			data: [''],
			axisLine: {
				show: false
			},
			axisTick: {
				show: false
			}
		}],
		xAxis: {
			type: 'value',
			axisLabel: {
				formatter: '{value}ms'
			},
			axisLine: {
				show: false
			},
			axisTick: {
				show: false
			}
		},
		tooltip: {
			formatter: '{a}: {c}'
		},
		legend: {
			selectedMode: false,
			right: 0,
			top: 20
		},
		grid: {
			containLabel: true,
			width: "96%",
			height: 60,
			left: 10,
			top: 80
		},
		series: [{
			name: "响应时长 ms",
			data: [value],
			type: 'bar',
			yAxisIndex: 0,
			stack: "range",
			silent: true,
			barWidth: 40,
			color: "#4b95f1"
		}]
	};
	window.myChartWZTZDTU = echarts.init(document.getElementById('wztzdtu'));
	window.myChartWZTZDTU.setOption(option);
}
///地图中的扇形
function ClientEnvironmentEcharts(platformTypes) {
	var data = [];
	for (var i in platformTypes) { //用javascript的for/in循环遍历对象的属性 
		var replist = {
			value: platformTypes[i],
			name: i,

		};
		data.push(replist);
	}

	var isHavIos = data.filter(item => item.name == "ios").length > 0;
	var isHavAndroid = data.filter(item => item.name == "android").length > 0;
	var isHavWindow = data.filter(item => item.name == "windows").length > 0;
	if (!isHavIos) {
		data.push({
			value: 0,
			name: 'ios'
		});
	}
	if (!isHavAndroid) {
		data.push({
			value: 0,
			name: 'android'
		});
	}
	if (!isHavWindow) {
		data.push({
			value: 0,
			name: 'windows'
		});
	}

	var option = {
		tooltip: {
			trigger: 'item',
			formatter: '{b} : {c} ({d}%)'
			//formatter: '{a} <br/>{b} : {c} ({d}%)'
		},
		series: [{
			name: '客户端环境',
			type: 'pie',
			radius: '54%',
			center: ['50%', '42%'],
			data: data,
			label: {
				position: 'outer',
				alignTo: 'labelLine',
				bleedMargin: 5
			},
			top: 0,
			bottom: 0
		}]
	};

	window.myChartSXTU = echarts.init(document.getElementById('sxtu'));
	window.myChartSXTU.setOption(option);
}

function ClienttypeEcharts(platformTypes) {
	var data = [];
	for (var i in platformTypes) { //用javascript的for/in循环遍历对象的属性 
		var replist = {
			value: platformTypes[i],
			name: i,

		};
		data.push(replist);
	}

	var isHavApp = data.filter(item => item.name == "app").length > 0;
	var isHavMinApp = data.filter(item => item.name == "minapp").length > 0;
	var isHavBrowser = data.filter(item => item.name == "browser").length > 0;

	if (!isHavApp) {
		data.push({
			value: 0,
			name: 'app'
		});
	}
	if (!isHavMinApp) {
		data.push({
			value: 0,
			name: 'minapp'
		});
	}
	if (!isHavBrowser) {
		data.push({
			value: 0,
			name: 'browser'
		});
	}

	var option = {
		tooltip: {
			trigger: 'item',
			formatter: '{b} : {c} ({d}%)'
			//formatter: '{a} <br/>{b} : {c} ({d}%)'
		},
		series: [{
			name: '客户端类型',
			type: 'pie',
			radius: '60%',
			center: ['50%', '40%'],
			data: data,
			label: {
				position: 'outer',
				alignTo: 'labelLine',
				bleedMargin: 5
			},
			top: 0,
			bottom: 0
		}]
	};

	window.myChartSXTULX = echarts.init(document.getElementById('sxtulx'));
	window.myChartSXTULX.setOption(option);
}

function failureRateEcharts(FailureRate) {
	var value = 0;
	if (FailureRate) {
		var successCount = FailureRate[0].successCount ? FailureRate[0].successCount : 0
		var runCount = FailureRate[0].runCount ? FailureRate[0].runCount : 0
		value = (runCount - successCount) / runCount * 100;
		value = value ? value.toFixed(2) : 0;
	}
	var option = {
		title: {
			text: '故障率'
		},
		series: [{
			type: 'gauge',
			center: ['50%', '80%'],
			startAngle: 190,
			endAngle: -10,
			min: 0,
			max: 100,
			splitNumber: 10,
			itemStyle: {
				color: 'red'
			},
			progress: {
				show: true,
				width: 20
			},
			pointer: {
				show: false
			},
			axisLine: {
				lineStyle: {
					width: 20
				}
			},
			axisTick: {
				distance: -30,
				splitNumber: 5,
				lineStyle: {
					width: 2,
					color: '#999'
				}
			},
			splitLine: {
				distance: -36,
				length: 4,
				lineStyle: {
					width: 2,
					color: '#999'
				}
			},
			axisLabel: {
				distance: 0,
				color: '#999',
				fontSize: 10
			},
			anchor: {
				show: false
			},
			title: {
				show: false
			},
			detail: {
				valueAnimation: true,
				width: '30%',
				lineHeight: 20,
				borderRadius: 8,
				offsetCenter: [0, '-10%'],
				fontSize: 13,
				fontWeight: 'bolder',
				formatter: '{value} %',
				color: 'auto'
			},
			//radius: '100%',  //环形的大小
			data: [{
				value: value
			}]
		},
		{
			type: 'gauge',
			center: ['50%', '80%'],
			startAngle: 190,
			endAngle: -10,
			min: 0,
			max: 100,
			itemStyle: {
				color: '#FD7347'
			},
			progress: {
				show: true,
				width: 20
			},
			pointer: {
				show: false
			},
			axisLine: {
				show: false
			},
			axisTick: {
				show: false
			},
			splitLine: {
				show: false
			},
			axisLabel: {
				show: false
			},
			detail: {
				show: false
			},
			data: [{
				value: value
			}]
		}
		]
	};
	window.myChartYBP = echarts.init(document.getElementById('ybp'));
	myChartYBP.setOption(option);
}

function UserCityMap(data) {
	//值

	var height = "6%";
	if (1 < seriesData.length && seriesData.length < 3) {
		height = "6%";
	} else if (3 < seriesData.length && seriesData.length < 6) {
		height = "12%";
	} else if (6 < seriesData.length && seriesData.length < 10) {
		height = "20%";
	} else if (10 < seriesData.length && seriesData.length < 15) {
		height = "30%";
	} else if (15 < seriesData.length) {
		height = "40%";
	}

	data.sort(function (a, b) {
		return a.value - b.value;
	});


	var categoryData = [];
	var barData = [];

	for (var i = 0; i < data.length; i++) {
		if (data[i].name == "none") {
			categoryData.push("Other");
		} else {
			categoryData.push(data[i].name);
		}
		barData.push(data[i].value);
	}


	var option = {
		backgroundColor: "#FFFFFF",
		animation: true,
		animationDuration: 1e3,
		animationEasing: "cubicInOut",
		animationDurationUpdate: 1e3,
		animationEasingUpdate: "cubicInOut",
		title: [{
			id: "statistic",
			text: "在线用户城市",
			right: -4,
			top: 30,
			width: '60px',
			textStyle: {
				color: "#323232",
				fontSize: 14
			}
		}],
		geo: {
			map: "china",
			center: ['40%', '40%'],
			zoom: 1,
			label: {
				normal: {
					show: true, //显示省份标签
					textStyle: {
						color: "#895139"
					} //省份标签字体颜色
				},
				emphasis: { //对应的鼠标悬浮效果
					show: true,
					textStyle: {
						color: "#323232"
					}
				}
			},
			itemStyle: {
				normal: {
					borderWidth: .5, //区域边框宽度
					borderColor: '#D2B48C', //区域边框颜色
					areaColor: "#F8F8FF", //区域颜色
				},
				emphasis: {
					borderWidth: .5,
					borderColor: '#FF8C00',
					areaColor: "#ece39e",
				}
			}
		},
		tooltip: {
			trigger: "item"
		},
		grid: {
			right: 30,
			top: 60,
			bottom: 10,
			width: "6%",
			height: height,
		},
		tooltip: {
			trigger: 'item',
			formatter: function (params) { // 鼠标滑过显示的数据

				var toolTiphtml = ''
				for (var i = 0; i < data.length; i++) {

					if (params.name == data[i].name) {
						toolTiphtml += data[i].name + '<br>分布人数：' + data[i].value;
					}
				}

				return toolTiphtml;

			}
		},
		xAxis: {
			type: "value",
			scale: true,
			position: "top",

			boundaryGap: false,
			splitLine: {
				show: false
			},
			axisLine: {
				show: false
			},
			axisTick: {
				show: false
			},
			axisLabel: {
				show: false,
				margin: 2,
				textStyle: {
					color: "#aaa"
				}
			}
		},
		yAxis: {
			type: "category",
			nameGap: 16,
			axisLine: {
				show: true,
				lineStyle: {
					color: "#ddd"
				}
			},
			axisTick: {
				show: false,
				lineStyle: {
					color: "#ddd"
				}
			},
			axisLabel: {
				interval: 0,

				textStyle: {
					color: "#323232"
				}
			},
			data: categoryData
		},
		series: [{
			id: "bar",
			zlevel: 2,

			type: "bar",
			symbol: "none",
			itemStyle: {
				normal: {
					color: "#778899",

				}
			},
			label: {
				show: true,
				position: "right"
			},
			data: data
		},
		{
			name: '点',
			type: 'scatter',
			coordinateSystem: 'geo',
			symbol: 'pin', //气泡
			symbolSize: function (val) {
				return 30;
			},
			label: {
				normal: {
					show: true,
					formatter: function (params) {
						return params.data.value[2];
					},
					textStyle: {
						color: '#fff',
						fontSize: 9
					}
				}
			},
			itemStyle: {
				normal: {
					color: '#F62157' //标志颜色'#F62157'
				}
			},
			zlevel: 6,
			data: convertDats(data),
		}
		]
	};

	window.chartmainmap = echarts.init(document.getElementById('mainmap'));
	window.chartmainmap.setOption(option);
}


window.addEventListener("resize", function () {
	window.chartmainmap.resize();
	window.myChartYBP.resize();
	window.myChartSXTULX.resize();
	window.myChartSXTU.resize();
	window.myChartWZTZDTU.resize();
	window.myChartYZTZDTU.resize();
	window.myChartSTATEZB.resize();
	window.myChartzHEXTU.resize();
});
